package com.dikang.keer.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dikang.common.utils.PageUtils;
import com.dikang.common.utils.Query;
import com.dikang.keer.product.controller.CategoryBrandRelationController;
import com.dikang.keer.product.entity.CategoryBrandRelationEntity;
import com.dikang.keer.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.dikang.keer.product.dao.BrandDao;
import com.dikang.keer.product.entity.BrandEntity;
import com.dikang.keer.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        if (StringUtils.isEmpty(key)){
            IPage<BrandEntity> page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    new QueryWrapper<BrandEntity>()
            );
            return new PageUtils(page);
        }else{
            QueryWrapper<BrandEntity> wrapper =new QueryWrapper<>();
           wrapper.and( (obj)-> obj.eq("brand_id",key).or().like("name",key));
            IPage<BrandEntity> page = this.page(
                    new Query<BrandEntity>().getPage(params),
                   wrapper
            );
            return new PageUtils(page);
        }
    }

    /**
     * 修改连表
     * @param brand
     */
    @Override
    @Transactional
    public void updateBrandEntity(BrandEntity brand) {
        // 修改brand数据和CategoryAndBrand数据
       this.updateById(brand);
        UpdateWrapper<CategoryBrandRelationEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("brand_id",brand.getBrandId());
        wrapper.set("brand_name",brand.getName());
        categoryBrandRelationService.update(wrapper);
    }

}